package repo

import (
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/mattn/go-sqlite3"
	"github.com/spf13/viper"
	"storeManageApi/models/dbModels"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

var Engin *xorm.Engine

// InitDbEngin
//
//	@Description: 初始化数据库
func InitDbEngin() {
	var dbType string = viper.GetString("config.dbType")
	var sqlUrl string
	if dbType == "mysql" {
		//	mysql
		sqlUrl = viper.GetString("mysql.user") + ":" + viper.GetString("mysql.password") + "@tcp(" + viper.GetString("mysql.host") + ":" + viper.GetString("mysql.port") + ")/" + viper.GetString("mysql.databaseName") + "?charset=utf8&parseTime=True&loc=Local"
	} else {
		//	sqlite3
		sqlUrl = viper.GetString("sqlite.url")
	}
	var err error
	println(dbType, "->", sqlUrl)
	Engin, err = xorm.NewEngine(dbType, sqlUrl)
	var showSql = viper.GetBool("config.showSQL")
	if showSql {
		Engin.ShowSQL(true)
		Engin.Logger().SetLevel(log.LOG_DEBUG)
	}
	println("链接数据库成功")
	//	同步表
	err = Engin.Sync2(new(dbModels.GoodsConfigs), new(dbModels.StoreNotes), new(dbModels.InNotes), new(dbModels.OutNotes))
	if err != nil {
		panic("aa")
	}
}
